import axios from "axios"
import config from "../config/index"
import { ElMessage } from "element-plus"
import router from "../router"
import storage from "./storage"

const TOKEN_ERROR = "token认证失败，请重新登录"
const NETWORK_ERROR = "网络请求异常，请稍候重试"

// 创建axios的实例对象 添加配置
const service = axios.create({
    baseURL: config.baseApi,
    timeout: 8000
})

// 请求的拦截
service.interceptors.request.use((req) => {
    const header = req.headers;
    const { token = "" } = storage.getItem("userInfo") || {};
    if (!header.Authorization) {
        header.Authorization = "Bearer " + token;
    }
    return req;
})

// 相应拦截
service.interceptors.response.use((res) => {
    const { code, data, msg } = res.data;
    if (code === 200) {
        return data;
    } else if (code === 50001) {
        ElMessage.error(TOKEN_ERROR)
        setTimeout(() => {
            router.push("/login")
        }, 1500)
        return Promise.reject(TOKEN_ERROR)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
})

/**
 * 核心的request函数
 * @param {*} options 
 * {
 *   method,
 *   mock,
 *   data,
 *   url
 * }
 */
function request(options) {
    options.method = options.method || "get";
    if (options.method.toLowerCase() === "get") {
        options.params = options.data;
    }
    let isMock = config.mock;
    if (typeof options.mock != 'undefined') {
        isMock = options.mock
    }
    if (config.env === "production") {
        service.defaults.baseURL = config.baseApi;
    }
    if (config.env === "dev") {
        service.defaults.baseURL = config.baseApi;
    }
    if (isMock) {
        service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
    }

    return service(options)
}


["get", "post", "put", "delete", "patch"].forEach((item) => {
    request[item] = (url, data, options) => {
        return request({
            method: item,
            url,
            data,
            ...options
        })
    }
})

export default request;